/*
You have to create a function that takes a positive integer number and returns the next bigger number formed by the same digits:

nextBigger(12)==21
nextBigger(513)==531
nextBigger(2017)==2071
If no bigger number can be composed using those digits, return -1:

nextBigger(9)==-1
nextBigger(111)==-1
nextBigger(531)==-1
*/

function quickSort(arr) {
    //如果数组<=1,则直接返回
    if (arr.length <= 1) { return arr; }
    var pivotIndex = Math.floor(arr.length / 2);
    //找基准，并把基准从原数组删除
    var pivot = arr.splice(pivotIndex, 1)[0];
    //定义左右数组
    var left = [];
    var right = [];

    //比基准小的放在left，比基准大的放在right
    for (var i = 0; i < arr.length; i++) {
        if (arr[i] <= pivot) {
            left.push(arr[i]);
        }
        else {
            right.push(arr[i]);
        }
    }
    //递归
    return quickSort(left).concat([pivot], quickSort(right));
}

const fn = (source, result, r) => {
    if (source.length == 0) {
        r.push(result.join(''));
    } else {
        for (let i = 0; i < source.length; i++) {
            fn(source.slice(0, i).concat(source.slice(i + 1)), result.concat(source[i]), r);
        }
    }
};

const perm = (arr, r) => fn(arr, [], r);

function nextBigger(n) {
    let time = new Date().getTime();
    let r = [], result = -1;
    perm(n.toString(), r);
    console.log("perm time:", new Date().getTime() - time);
    r = quickSort(r);
    console.log("sort time:", new Date().getTime() - time);
    for (let i = 0; i < r.length; i++) {
        let rNumber = +r[i];
        if (n - rNumber < 0) {
            result = rNumber;
            break;
        }
    }
    console.log("next bigger time:", new Date().getTime() - time);
    return result;
}

console.log(nextBigger(2005332));
